﻿using System;
using System.Net;
using System.Windows;
using Skyper.Phone.View;

namespace Skyper.Phone.Presenters {
	public class LoginPresenter : Presenter<ILoginView> {
		#region Constructor
		public LoginPresenter(ILoginView view)
			: base(view) {

				this.View.Loaded += new RoutedEventHandler(View_Loaded);
				this.View.Unloaded += new RoutedEventHandler(View_Unloaded);


		}
		#endregion
		#region Private
		private void View_Loaded(object sender, RoutedEventArgs e) {
			Globals.Sync.StatusChanged += (Sync_StatusChanged);
			this.View.Login += (View_Login);
		}
		private void View_Unloaded(object sender, RoutedEventArgs e) {
			Globals.Sync.StatusChanged += (Sync_StatusChanged);
			this.View.Login -= (View_Login);
		}
		private void Sync_StatusChanged(object sender, EventArgs e) {
			this.View.IsBusy = false;
			this.View.IsEnabled = true;
			if (Globals.Sync.Status == Model.SkypeStatus.Online) {
				//Navigate
				App.Navigate("/View/Pages/HomePage.xaml");
			} else {
				MessageBox.Show("Unable to connect to remote server.");
			}
		}
		private void View_Login(object sender, RoutedEventArgs e) {
			this.View.IsEnabled = false;
			this.View.IsBusy = true;
			Globals.Config.Hostname = this.View.Hostname;
			Globals.Config.Password = this.View.Password;
			Globals.Config.Remmember = this.View.Remmember;

			Globals.Sync.Connect(this.View.Hostname);
			Globals.Sync.Login(this.View.Password);
		}
		#endregion
		#region Protected

		#endregion
		#region Public
		public sealed override void Refresh() {
			this.View.Hostname = Globals.Config.Hostname;
			this.View.Password = Globals.Config.Password;
			this.View.Remmember = Globals.Config.Remmember;
			base.Refresh();
		}
		#endregion
	}
}
